package d10_api_object;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;



public class SymmetricEncryption {
    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;

public static void main(String[] args) throws Exception {
    String keyString = "ThisIsASecretKey256BitsLong"; // 实际使用时应更复杂且安全
    Key key = generateKey(keyString);

    String originalText = "Hello, this is a secret message!";
    String encryptedText = encrypt(originalText, key);
    System.out.println("Encrypted: " + encryptedText);

    String decryptedText = decrypt(encryptedText, key);
    System.out.println("Decrypted: " + decryptedText);
}


   public static String decrypt(String cipherText, Key key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);

    byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
    byte[] decryptedBytes = cipher.doFinal(decodedBytes);
    return new String(decryptedBytes);
}
public static String encrypt(String plainText, Key key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static Key generateKey(String keyString) throws Exception {
    byte[] keyBytes = new byte[256 / 8];
    // 这里简单地使用给定字符串的字节作为密钥，实际应用中应使用更安全的方式生成密钥
    byte[] stringBytes = keyString.getBytes("UTF-8");
    System.arraycopy(stringBytes, 0, keyBytes, 0, Math.min(stringBytes.length, keyBytes.length));
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    return keySpec;
}

}
